<template>
    <el-dialog v-model="show" :title="t('选择课程')" :close-on-press-escape="false" :close-on-click-modal="false"
        :show-close="false" :draggable="true" @before-close="() => false" append-to-body style="width: 70%;">
        <FormBase>
            <QueryBase @onSearch="doQuery" style="width:96%">
                <template #search>
                    <el-form :inline="true" :model="queryForm">
                        <el-form-item :label="t('课程名称')">
                            <el-input v-model="queryForm.name" placeholder="请输入" clearable v-enter="doQuery" />
                        </el-form-item>
                        <el-form-item :label="t('课程分类')">
                            <el-cascader v-model="queryForm.categoryId" :options="categoryOptions" :props="{
                                checkStrictly: false
                            }" filterable clearable />
                        </el-form-item>
                    </el-form>
                </template>
                <template #operation>
                    <div></div>
                </template>
                <el-table ref="multipleTableRef" :data="tableData" :border="true" header-row-class-name="table-header"
                    height="400">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="name" :label="t('名称')" width="180" />
                    <el-table-column prop="categoryText" :label="t('分类')" width="180" />
                    <el-table-column prop="originImg" :label="t('封面')">
                        <template #default="scope">
                            <v-image :src="scope.row.originImg" :style="{ width: '45px', height: '45px' }"
                                :disabled="true"></v-image>
                        </template>
                    </el-table-column>
                </el-table>
            </QueryBase>
            <div class="course-result-pn">
                <VPageNavigation :total="total" @on-size-changed="handleSizeChange"
                    @on-page-changed="handleCurrentChange">
                </VPageNavigation>
            </div>
            <template #submit>
                <el-button type="primary" size="large" @click="handleSelected" :icon="Check">{{ t('确定') }}</el-button>
                <el-button size="large" @click="() => show = false" :icon="Close">{{ t('取消') }}</el-button>
            </template>
        </FormBase>
    </el-dialog>
</template>
<script setup lang="ts">
import { Check, Close } from '@element-plus/icons-vue'
import { Ref, onMounted, reactive, ref, watch, defineEmits, defineModel, nextTick, defineProps } from 'vue';
import { t } from '@/common/locale'
import { queryList } from '@/api/course';
import { getCategoryMap, getCategoryOptions } from '@/api/category'
import elHelper from '@/common/elHelper';
import VPageNavigation from '@/components/other/VPageNavigation.vue';
import QueryBase from '@/components/layout/QueryBase.vue';
import { ElTable } from 'element-plus';
import comFunc from '@/common/comFunc';
import FormBase from '../layout/FormBase.vue';

const props = defineProps({
    //指定是否专区未与专家绑定的资料
    useUnRelatedData: {
        type: Boolean,
        default: false
    },
    onQuery: {
        type: Function,
        default: null
    }
})
const model = defineModel({ type: Array<string>, default: [] })
const show = defineModel('show', { type: Boolean })

const multipleTableRef = ref()
const queryForm: CourseQueryForm = reactive({
    name: '',
    categoryId: [],
})
const page = ref(1)
const pageSize = ref(0)
const tableData: Ref<CourseDataModel[]> = ref([])
const total = ref(0)
const categoryOptions: Ref<CategorySelectOption[]> = ref([])

const emit = defineEmits(['onSelected'])

watch(() => show.value, (val) => {
    if (val) {
        nextTick(() => {
            doQuery()
        })
    }
})
watch(() => model.value, (val) => {
    if (!val) model.value = []
})

const setSelected = () => {
    if (!model.value) return
    if (!multipleTableRef.value) return
    nextTick(() => {
        multipleTableRef.value!.clearSelection()
        tableData.value.forEach((item) => {
            if (model.value?.find(v => v === item.objectId)) {
                multipleTableRef.value!.toggleRowSelection(item, true)
            }
        })
    })
}
const doQuery = async () => {
    const loading = elHelper.showLoading()
    let categoryId = ''
    if (Array.isArray(queryForm.categoryId)) {
        let arr = queryForm.categoryId as string[]
        categoryId = arr[arr.length - 1]
    }
    const re = await queryList({
        name: queryForm.name,
        categoryId: categoryId,
        pageSize: pageSize.value,
        to: page.value
    })
    if (re.isSuccess) {
        let list = re.data || []
        const map = await getCategoryMap('COURSE')
        list.forEach((item) => {
            const opt = map.get(item.categoryId)
            item.categoryText = opt ? opt : ''
        })
        tableData.value = list
        total.value = re.totalRow || 0
        page.value = re.pageNum || 1
        setSelected()
    } else {
        elHelper.showErrorMsg(re.msg)
    }
    elHelper.closeLoading(loading)
}

const handleSizeChange = (val: number) => {
    pageSize.value = val
    doQuery()
}
const handleCurrentChange = (val: number) => {
    page.value = val
    doQuery()
}
const handleSelected = () => {
    const rows = multipleTableRef.value?.getSelectionRows()
    rows.forEach(r => {
        if (!model.value.find(v => v === r.objectId)) {
            model.value.push(r.objectId)
        }
    })
    emit('onSelected', multipleTableRef.value?.getSelectionRows())
    show.value = false
}
onMounted(async () => {
    const l = await getCategoryOptions('COURSE')
    categoryOptions.value = l
    doQuery()
})
</script>
<style scoped lang="scss">
.course-result-pn {
    padding-top: 15px;
    display: flex;
    justify-content: flex-end;
}
</style>